package com.veo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.veo.entity.Cart;
import com.veo.entity.CartVo;
import com.veo.entity.User;
import com.veo.entity.UserCartVo;
import com.veo.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 加入购物车
     */
    @RequestMapping("/add")
    @ResponseBody
    public String add(Cart cart, HttpSession session){
        User user = (User) session.getAttribute("user");
        cart.setUserId(user.getId());
        //判断购物车中是否已经存在该条记录
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId());
        queryWrapper.eq("book_id",cart.getBookId());
        Cart queryCart = cartService.getOne(queryWrapper);
        if (queryCart == null){
            cartService.save(cart);
        }else {
            queryCart.setCount(queryCart.getCount() + cart.getCount());
            cartService.updateById(queryCart);
        }
        return "success";
    }

    /**
     * 查询用户的购物车数据
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        List<CartVo> cartVoList = cartService.findCartVoById(user.getId());
        UserCartVo userCartVo = cartService.wrapCart(cartVoList);
        session.setAttribute("userCartInfo",userCartVo);
        model.addAttribute("cartList",cartVoList);
        return "cart";
    }

    /**
     * 购物车商品的信息的修改
     */
    @ResponseBody
    @RequestMapping("/update")
    public String update(Cart cart,HttpSession session){
        cartService.updateById(cart);
        User user = (User) session.getAttribute("user");
        List<CartVo> cartVoList = cartService.findCartVoById(user.getId());
        UserCartVo userCartVo = cartService.wrapCart(cartVoList);
        session.setAttribute("userCartInfo",userCartVo);

        double price = cartService.getCartItemTotal(cartVoList);
        return String.valueOf(price);
    }

    /**
     * 删除购物中的记录
     */
    @ResponseBody
    @RequestMapping("/delete")
    public String delete(String ids){
        return cartService.batchDelete(ids);
    }
}
